<template>
  <div class="knowledge-main">
    <div class="top-bar">
      <el-input v-model="searchText" placeholder="在所有空间中搜索" class="search-input" clearable />
      <el-button v-auth="'space:manage'" type="primary" @click="openGroupDialog">分组管理</el-button>
      <el-button v-auth="'space:manage'" @click="createNewSpace">+ 新建空间</el-button>
    </div>

    <template v-if="filteredGroups.length > 0">
      <section class="section" v-for="group in filteredGroups" :key="group.FId">
        <div class="group-header">
          <h3>{{ group.FName }}</h3>
          <span class="space-count">{{ getSpacesByGroup(group.FId).length }}个空间</span>
        </div>
        <div class="card-list">
          <KnowledgeCard
            v-for="item in getSpacesByGroup(group.FId)"
            :key="item.FId"
            :item="item"
            @card-click="goDetail"
            @star-change="handleStarChange"
            @action="handleCardAction"
          />
          <div class="empty-tip" v-if="getSpacesByGroup(group.FId).length === 0">该分组下暂无知识空间</div>
        </div>
      </section>
    </template>

    <el-empty description="暂无分组数据" v-else />

    <!-- 分组管理对话框 -->
    <el-dialog title="分组管理" v-model="groupDialogVisible" width="500px">
      <el-table :data="groups" border class="group-table" v-loading="loading">
        <el-table-column prop="FName" label="分组名称" />
        <el-table-column label="空间数量" width="100">
          <template #default="{ row }">{{ getSpacesByGroup(row.FId).length }}</template>
        </el-table-column>
        <el-table-column label="操作" width="140">
          <template #default="scope">
            <el-button type="success" size="small" @click="editGroup(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteGroup(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="dialog-footer">
        <el-button type="primary" @click="addGroup">+ 新增分组</el-button>
      </div>
    </el-dialog>

    <!-- 分组编辑对话框 -->
    <el-dialog :title="editForm.FId ? '编辑分组' : '新增分组'" v-model="editDialogVisible" width="400px">
      <el-form :model="editForm" label-width="80px" ref="editFormRef" :rules="rules">
        <el-form-item label="分组名称" prop="FName">
          <el-input v-model="editForm.FName" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="默认分组">
          <el-switch v-model="editForm.FIsdefault" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveGroup">保存</el-button>
      </template>
    </el-dialog>

    <!-- 创建/编辑空间对话框 -->
    <el-dialog :title="editSpaceMode ? '编辑知识空间' : '新建知识空间'" v-model="spaceDialogVisible" width="600px">
      <el-form :model="spaceForm" label-width="100px" ref="spaceFormRef" :rules="spaceRules">
        <el-form-item label="空间名称" prop="FTitle">
          <el-input v-model="spaceForm.FTitle" placeholder="请输入空间名称" />
        </el-form-item>
        <el-form-item label="空间描述" prop="FDescription">
          <el-input v-model="spaceForm.FDescription" type="textarea" :rows="3" placeholder="请输入空间描述" />
        </el-form-item>
        <el-form-item label="封面图片">
          <UploadImg
            v-model:image-url="spaceForm.FCover"
            :api="uploadImgApi"
            :width="'100%'"
            :min-width="'200px'"
            :height="'200px'"
            :border-radius="'4px'"
          />
        </el-form-item>
        <el-form-item label="标签">
          <el-input v-model="spaceForm.FTag" placeholder="多个标签用逗号分隔" @change="handleTagInput" />
        </el-form-item>
        <el-form-item label="所属分组" prop="FGroupId">
          <el-select v-model="spaceForm.FGroupId" placeholder="请选择分组" style="width: 100%">
            <el-option v-for="group in groups" :key="group.FId" :label="group.FName" :value="group.FId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="spaceDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSaveSpace">确定</el-button>
      </template>
    </el-dialog>

    <!-- 管理员管理对话框 -->
    <el-dialog :title="`空间管理员管理 - ${currentSpace?.FTitle}`" v-model="adminDialogVisible" width="500px">
      <div class="admin-management">
        <div class="admin-list">
          <h4>当前管理员</h4>
          <el-table :data="spaceAdmins" border>
            <el-table-column prop="FUsername" label="用户名" />
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button size="small" type="danger" @click="removeAdmin(scope.row.FUserId)"> 移除 </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="add-admin">
          <el-button type="primary" @click="openAddAdminDialog">
            <el-icon><Plus /></el-icon>
            添加管理员
          </el-button>
        </div>
      </div>

      <template #footer>
        <el-button @click="adminDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 添加管理员对话框 -->
    <el-dialog title="添加管理员" v-model="addAdminDialogVisible" width="600px" @closed="handleAddAdminDialogClosed">
      <div class="user-select-container">
        <el-input v-model="userSearchText" placeholder="搜索用户" clearable style="margin-bottom: 20px" />

        <el-table :data="filteredUsers" border highlight-current-row @current-change="handleUserSelect" style="width: 100%">
          <el-table-column prop="FUsername" label="用户名" width="150" />
          <el-table-column label="部门">
            <template #default="{ row }">
              {{ row.department?.FName || "无" }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <el-button @click="addAdminDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddAdmin" :disabled="!selectedUser"> 确认添加 </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { FormInstance } from "element-plus";
import KnowledgeCard from "./components/KnowledgeCard.vue";
import UploadImg from "@/components/Upload/Img.vue";
import { useUserStore } from "@/stores/modules/user";
import { useDocumentStore } from "@/stores/modules/document";

import {
  getGroupListApi,
  addGroupApi,
  updateGroupApi,
  deleteGroupApi,
  getSpaceListByGroupApi,
  createSpaceApi,
  updateSpaceApi,
  deleteSpaceApi,
  toggleFavoriteApi,
  getSpaceAdminsApi,
  addSpaceAdminApi,
  removeSpaceAdminApi
} from "@/api/modules/space";

import { getAllUserList } from "@/api/modules/admin";
import type { Space } from "@/api/interface/space";
import type { Admin } from "@/api/interface/admin";

const router = useRouter();
const userStore = useUserStore();
const documentStore = useDocumentStore();

// 数据状态
const searchText = ref("");
const loading = ref(false);
const groups = ref<Space.Group[]>([]);
const knowledgeSpaces = ref<Space.SpaceItem[]>([]);

// 对话框控制
const groupDialogVisible = ref(false);
const editDialogVisible = ref(false);
const spaceDialogVisible = ref(false);
const adminDialogVisible = ref(false);
const addAdminDialogVisible = ref(false);
const editSpaceMode = ref(false);

// 表单引用
const editFormRef = ref<FormInstance>();
const spaceFormRef = ref<FormInstance>();

// 表单数据
const editForm = ref({
  FId: undefined as number | undefined,
  FName: "",
  FIsdefault: 0
});

const spaceForm = ref({
  FId: "",
  FTitle: "",
  FDescription: "",
  FGroupId: undefined as number | undefined,
  FCover: "",
  FTag: ""
});

// 管理员管理相关状态
const currentSpace = ref<Space.SpaceItem | null>(null);
const spaceAdmins = ref<Space.SpaceAdmin[]>([]);
const userList = ref<Admin.UserItem[]>([]);
const userSearchText = ref("");
const selectedUser = ref<Admin.UserItem | null>(null);

// 验证规则
const rules = {
  FName: [
    { required: true, message: "请输入分组名称", trigger: "blur" },
    { min: 1, max: 20, message: "长度在1到20个字符", trigger: "blur" }
  ]
};

const spaceRules = {
  FTitle: [{ required: true, message: "请输入空间名称", trigger: "blur" }],
  FDescription: [{ required: true, message: "请输入空间描述", trigger: "blur" }],
  FGroupId: [{ required: true, message: "请选择分组", trigger: "change" }]
};

// 计算属性
const filteredGroups = computed(() => {
  if (!searchText.value) return groups.value;

  const searchLower = searchText.value.toLowerCase();

  return groups.value.filter(group => {
    const groupNameMatch = group.FName.toLowerCase().includes(searchLower);
    const spaceMatch = getSpacesByGroup(group.FId).some(space => {
      return space.FTitle.toLowerCase().includes(searchLower) || (space.FTag && space.FTag.toLowerCase().includes(searchLower));
    });

    return groupNameMatch || spaceMatch;
  });
});

// 计算过滤后的用户列表
const filteredUsers = computed(() => {
  const searchText = userSearchText.value.toLowerCase();
  const adminIds = spaceAdmins.value.map(admin => admin.FUserId);

  return userList.value.filter(
    user =>
      !adminIds.includes(user.FUserId) &&
      (user.FUsername.toLowerCase().includes(searchText) ||
        user.FEmail?.toLowerCase().includes(searchText) ||
        user.department?.FName.toLowerCase().includes(searchText))
  );
});

// 图片上传API
const uploadImgApi = (formData: FormData) => {
  return new Promise((resolve, reject) => {
    const file = formData.get("file") as File;
    if (!file) {
      reject(new Error("请选择文件"));
      return;
    }

    const reader = new FileReader();
    reader.onload = () => {
      resolve({
        data: {
          fileUrl: reader.result as string
        }
      });
    };
    reader.onerror = () => {
      reject(new Error("图片加载失败"));
    };
    reader.readAsDataURL(file);
  });
};

// 标签输入处理
const handleTagInput = (value: string) => {
  spaceForm.value.FTag = value.replace(/\s+/g, "");
};

// 获取分组列表
const fetchGroups = async () => {
  loading.value = true;
  try {
    const { data } = await getGroupListApi();
    groups.value = data;
  } catch (error) {
    ElMessage.error("获取分组列表失败");
  } finally {
    loading.value = false;
  }
};

// 获取空间列表
const fetchSpaces = async () => {
  try {
    const { data } = await getSpaceListByGroupApi({ FUserId: userStore.userInfo.FUserId });
    knowledgeSpaces.value = data;
  } catch (error) {
    ElMessage.error("获取空间列表失败");
  }
};

// 根据分组ID获取空间
const getSpacesByGroup = (groupId: number) => {
  return knowledgeSpaces.value.filter(space => space.FGroupId === groupId);
};

// 打开分组管理
const openGroupDialog = () => {
  groupDialogVisible.value = true;
};

// 添加分组
const addGroup = () => {
  editForm.value = { FId: undefined, FName: "", FIsdefault: 0 };
  editDialogVisible.value = true;
  nextTick(() => editFormRef.value?.clearValidate());
};

// 编辑分组
const editGroup = (group: Space.Group) => {
  editForm.value = { FId: group.FId, FName: group.FName, FIsdefault: group.FIsdefault || 0 };
  editDialogVisible.value = true;
  nextTick(() => editFormRef.value?.clearValidate());
};

// 删除分组
const deleteGroup = async (group: Space.Group) => {
  try {
    await ElMessageBox.confirm(`确定删除分组 "${group.FName}" 吗？`, "删除确认", { type: "warning" });
    if (group.FIsdefault == 1) {
      ElMessage.error("默认分组不能删除");
      return;
    }
    await deleteGroupApi({ FId: group.FId });
    ElMessage.success("删除成功");
    fetchGroups();
    fetchSpaces();
  } catch {
    // 用户取消删除
  }
};

// 保存分组
const saveGroup = () => {
  editFormRef.value?.validate(async valid => {
    if (!valid) return;

    try {
      if (editForm.value.FId) {
        await updateGroupApi({
          FId: editForm.value.FId,
          FName: editForm.value.FName,
          FIsdefault: editForm.value.FIsdefault
        });
      } else {
        await addGroupApi({
          FName: editForm.value.FName,
          FIsdefault: editForm.value.FIsdefault
        });
      }
      ElMessage.success("保存成功");
      editDialogVisible.value = false;
      fetchGroups();
    } catch (error) {
      ElMessage.error("保存失败");
    }
  });
};

// 新建空间
const createNewSpace = () => {
  editSpaceMode.value = false;
  spaceForm.value = {
    FId: "",
    FTitle: "",
    FDescription: "",
    FGroupId: undefined,
    FCover: "",
    FTag: ""
  };
  spaceDialogVisible.value = true;
  nextTick(() => spaceFormRef.value?.clearValidate());
};

// 编辑空间
const editSpace = (space: Space.SpaceItem) => {
  editSpaceMode.value = true;
  spaceForm.value = {
    FId: space.FId,
    FTitle: space.FTitle,
    FDescription: space.FDescription,
    FGroupId: space.FGroupId,
    FCover: space.FCover || "",
    FTag: space.FTag || ""
  };
  spaceDialogVisible.value = true;
  nextTick(() => spaceFormRef.value?.clearValidate());
};

// 保存空间
const confirmSaveSpace = () => {
  spaceFormRef.value?.validate(async valid => {
    if (!valid) return;

    try {
      if (editSpaceMode.value) {
        await updateSpaceApi({
          FId: spaceForm.value.FId,
          FTitle: spaceForm.value.FTitle,
          FDescription: spaceForm.value.FDescription,
          FGroupId: spaceForm.value.FGroupId!,
          FCover: spaceForm.value.FCover,
          FTag: spaceForm.value.FTag,
          FModifierId: userStore.userInfo.FUserId
        });
        ElMessage.success("更新成功");
      } else {
        await createSpaceApi({
          FCreatorId: userStore.userInfo.FUserId,
          FTitle: spaceForm.value.FTitle,
          FDescription: spaceForm.value.FDescription,
          FGroupId: spaceForm.value.FGroupId!,
          FCover: spaceForm.value.FCover || undefined,
          FTag: spaceForm.value.FTag || undefined
        });
        ElMessage.success("创建成功");
      }
      spaceDialogVisible.value = false;
      fetchSpaces();
    } catch (error) {
      ElMessage.error(editSpaceMode.value ? "更新失败" : "创建失败");
      console.error(error);
    }
  });
};

// 删除空间
const deleteSpace = async (space: Space.SpaceItem) => {
  try {
    await ElMessageBox.confirm(`确定删除空间 "${space.FTitle}" 吗？`, "删除确认", { type: "warning" });
    await deleteSpaceApi({ FId: space.FId });
    ElMessage.success("删除成功");
    fetchSpaces();
  } catch {
    // 用户取消删除
  }
};

// 打开管理员管理对话框
const openAdminManagement = async (space: Space.SpaceItem) => {
  currentSpace.value = space;
  adminDialogVisible.value = true;
  await fetchSpaceAdmins(space.FId);
};

// 获取空间管理员列表
const fetchSpaceAdmins = async (spaceId: string) => {
  try {
    const { data } = await getSpaceAdminsApi({ FSpaceId: spaceId });
    spaceAdmins.value = data;
  } catch (error) {
    ElMessage.error("获取管理员列表失败");
    console.error(error);
  }
};

// 获取所有用户列表
const fetchAllUsers = async () => {
  try {
    const { data } = await getAllUserList();
    userList.value = data;
  } catch (error) {
    ElMessage.error("获取用户列表失败");
    console.error(error);
  }
};

// 打开添加管理员对话框
const openAddAdminDialog = async () => {
  addAdminDialogVisible.value = true;
  selectedUser.value = null;
  userSearchText.value = "";
  await fetchAllUsers();
};

// 处理用户选择
const handleUserSelect = (user: Admin.UserItem) => {
  selectedUser.value = user;
};

// 确认添加管理员
const confirmAddAdmin = async () => {
  if (!currentSpace.value || !selectedUser.value) return;

  try {
    await addSpaceAdminApi({
      FSpaceId: currentSpace.value.FId,
      FUserId: selectedUser.value.FUserId
    });
    ElMessage.success("添加管理员成功");
    addAdminDialogVisible.value = false;
    await fetchSpaceAdmins(currentSpace.value.FId);
  } catch (error) {
    ElMessage.error("添加管理员失败");
    console.error(error);
  }
};

// 添加管理员对话框关闭处理
const handleAddAdminDialogClosed = () => {
  selectedUser.value = null;
  userSearchText.value = "";
};

// 移除管理员
const removeAdmin = async (userId: string) => {
  if (!currentSpace.value) return;

  try {
    await ElMessageBox.confirm("确定移除该管理员吗？", "提示", { type: "warning" });

    await removeSpaceAdminApi({
      FSpaceId: currentSpace.value.FId,
      FUserId: userId
    });

    ElMessage.success("移除管理员成功");
    await fetchSpaceAdmins(currentSpace.value.FId);
  } catch (error) {
    // 用户取消或操作失败
    console.error(error);
  }
};

// 处理卡片操作
const handleCardAction = ({ type, item }: { type: string; item: Space.SpaceItem }) => {
  switch (type) {
    case "edit":
      editSpace(item);
      break;
    case "delete":
      deleteSpace(item);
      break;
    case "permission":
      openAdminManagement(item);
      break;
  }
};

// 收藏状态变更
const handleStarChange = async ({ id, isStarred }: { id: string; isStarred: boolean }) => {
  try {
    await toggleFavoriteApi({
      FUserId: userStore.userInfo.FUserId,
      FSpaceId: id,
      FIsStarred: isStarred
    });
    const item = knowledgeSpaces.value.find(i => i.FId === id);
    if (item) item.FIsStarred = isStarred;
    ElMessage.success(isStarred ? "已收藏" : "已取消收藏");
  } catch (error) {
    ElMessage.error("操作失败");
  }
};

// 查看详情
const goDetail = async (item: Space.SpaceItem) => {
  try {
    await documentStore.initData();
    await documentStore.loadSpaceDetail(item.FId);
    await documentStore.checkSpaceAdmin();
    await documentStore.loadDocTree(item.FId);

    router.push({
      name: "knowledgeDetail",
      params: { id: item.FId },
      query: { groupId: item.FGroupId }
    });
  } catch (error) {
    ElMessage.error("加载空间数据失败，请重试");
    console.error(error);
  }
};

// 初始化数据
onMounted(() => {
  fetchGroups();
  fetchSpaces();
});
</script>

<style scoped lang="scss">
.knowledge-main {
  box-sizing: border-box;
  min-height: 100vh;
  padding: 16px;
  background: #f9fafb;
}
.top-bar {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 24px;
  .search-input {
    flex: 1;
    max-width: 300px;
  }
}
.section {
  padding: 16px;
  margin-bottom: 32px;
  background: #ffffff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgb(0 0 0 / 8%);
}
.group-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #2c3e50;
  }
  .space-count {
    margin-left: 12px;
    font-size: 12px;
    color: #909399;
  }
}
.card-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}
.empty-tip {
  width: 100%;
  padding: 20px;
  font-size: 14px;
  color: #909399;
  text-align: center;
}
.group-table {
  width: 100%;
  overflow: hidden;
  border-radius: 4px;
}
.dialog-footer {
  margin-top: 20px;
  text-align: center;
}
.admin-management {
  display: flex;
  flex-direction: column;
  gap: 24px;
  .admin-list,
  .add-admin {
    h4 {
      margin: 0 0 12px;
      font-size: 15px;
      color: #606266;
    }
  }
}
.user-select-container {
  display: flex;
  flex-direction: column;
  height: 400px;
  .el-table {
    flex: 1;
    overflow: auto;
  }
}
</style>
